package com._520it.day2._03_blob;



import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.junit.Test;
import com._520it.util.JdbcUtil;

//操作二进制的大数据类型
public class BlobTest {
	
	//把一张图片保存到数据库中
	@Test
	public void testWrite() throws Exception {
		Connection conn = JdbcUtil.getConn();
		String sql="INSERT INTO images(headImg) VALUES (?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setBlob(1, new FileInputStream("D:/outman.jpg"));
		ps.executeUpdate();
		JdbcUtil.close(conn, ps, null);
	}
	//把id为1的数据查询出来
	@Test
	public void testRead() throws Exception {
		Connection conn =JdbcUtil.getConn();
		String sql="SELECT * FROM images WHERE id=?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setLong(1, 1L);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			Blob blob = rs.getBlob("headImg");
	  		InputStream is = blob.getBinaryStream();
			Files.copy(is, Paths.get("D:/1234.png"));
		}
		
		JdbcUtil.close(conn, ps, rs);
	}
}
